// function LinkList() {
//   function Nodes(element) {}
// }

function LinkList1() {
  let length = 0;
  let head = null;
  function Nodes(element) {
    this.element = element;
    this.next = null;
  }
  //向链表尾部添加节点
  this.append = (element) => {
    let node = new Nodes(element);
    let current = null;
    if (head == null) {
      head = node;
    } else {
      current = head;
      while (current.next) {
        current = current.next;
      }
      current.next = node;
    }
    length++;
  };

  //从链表中移除元素
  this.remove = (position) => {
    if (position > -1 && position < length) {
      let current = head,
        previous,
        index = 0;
      if (position == 0) {
        head == current.next;
      } else {
        while (index++ < position) {
          previous = current;
          current = current.next;
        }
        previous.next = current.next;
      }
      length--;
      return current.element;
    } else {
      throw new Error("链表中暂无值");
    }
  };

  //在链表的任意位置中插件一个元素
  this.insertElement = (position, element) => {
    if (position > -1 && position <= length) {
      let node = new Nodes(element);
      let current = head,
        previous,
        index = 0;
      if (position == 0) {
        node.next = current;
        head = node;
      } else {
        while (index++ < position) {
          previous = current;
          current = current.next;
        }
        node.next = current;
        previous.next = node;
      }
      length++;
      return true;
    } else {
      throw new Error("插入错误");
    }
  };

  

  //返回链表的字符串
  this.toString = () => {
    let current = head,
      stringList = "";
    while (current) {
      stringList += JSON.stringify(current.element) + (current.next ? "\n" : "");
      current = current.next;
    }
    return stringList;
  };

  //查找元素
  this.indexOfList = (element) => {
    let current = head,index=0;
    while(current) {
      if(element === current.element) {
        return index;
      }
      index ++;
      current = current.next;
    }
    return -1;
  }

  //判空
  this.isEmpty = () => {
    return length === 0;
  }
  
  //长度
  this.size = () => {
    return length;
  }

  // 找链表头部
  this.getHead = () => {
    return head;
  };
}

let a1 = new LinkList1();
a1.append(12);
// a.append(12);
console.log(a1); 
a1.remove(0);
